package com.example.stray_animal_management_system.commonu.controller;

import com.example.stray_animal_management_system.commonu.service.AnimalService;
import com.example.stray_animal_management_system.commonu.service.HealthRecordService;
import com.example.stray_animal_management_system.commonu.service.RescueInfoService;
import com.example.stray_animal_management_system.entity.Animal;
import com.example.stray_animal_management_system.entity.HealthRecord;
import com.example.stray_animal_management_system.entity.RescueInfo;
import com.example.stray_animal_management_system.entity.RescueStory;
import com.example.stray_animal_management_system.volunteer.service.RescueStoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @description:   用户端功能
 * @author: panpan
 * @time: 2025/10/26
 */
@RestController
@RequestMapping("/api/animal")
@CrossOrigin
public class AnimalController {

    @Autowired
    private AnimalService animalService;

    @Autowired
    private HealthRecordService healthRecordService;

    @Autowired
    private RescueStoryService rescueStoryService;
    @Autowired
    private RescueInfoService rescueInfoServicel;

    /**
     *  查询所有动物
     *  */
    @GetMapping("/listAll")
    public Map<String, Object> list(@RequestParam(required = false) Integer status) {
        Map<String, Object> res = new HashMap<>();
        List<Animal> list = animalService.lambdaQuery()
                .eq(status != null, Animal::getStatus, status)
                .list();
        res.put("code", 200);
        res.put("msg", "查询成功");
        res.put("data", list);
        res.put("timestamp", System.currentTimeMillis());
        return res;
    }

    /**
     * 用户查询单个动物详情（含健康档案/故事）
     * */
    @GetMapping("/detail/{id}")
    public Map<String, Object> getDetail(@PathVariable Integer id) {
        Map<String, Object> res = new HashMap<>();
        Animal animal = animalService.getById(id);
        List<HealthRecord> healthRecords = healthRecordService.lambdaQuery()
                .eq(HealthRecord::getAnimalId, id)
                .list();
        RescueStory story = rescueStoryService.lambdaQuery()
                .eq(RescueStory::getAnimalId, id)
                .one();

        Map<String, Object> data = new HashMap<>();
        data.put("animal", animal);
        data.put("health", healthRecords);
        data.put("story", story);

        res.put("code", 200);
        res.put("msg", "查询成功");
        res.put("data", data);
        res.put("timestamp", System.currentTimeMillis());
        return res;
    }

    /** 新增救助动物（用户上报） */
    @PostMapping("/add")
    public Map<String, Object> addAnimal(@RequestBody Animal animal) {
        Map<String, Object> res = new HashMap<>();
        animal.setCreateTime(LocalDateTime.now());
        animal.setRescueTime(LocalDateTime.now());
        animal.setStatus(0); // 默认待救助
        boolean saved = animalService.save(animal);
        res.put("code", saved ? 200 : 500);
        res.put("msg", saved ? "添加成功" : "保存失败");
        return res;
    }

    /**
     * 用户救助图片上传接口
     *
     * */
    private static final String UPLOAD_DIR = "D:/upload/rescue_photos/";

    @PostMapping("/uploadPhotos")
    public Map<String, Object> uploadPhotos(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "rescueId", required = false) Long rescueId
    ) {
        Map<String, Object> res = new HashMap<>();

        if (files == null || files.length == 0) {
            res.put("code", 400);
            res.put("msg", "文件为空");
            return res;
        }

        // 创建上传目录
        File dir = new File(UPLOAD_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        List<String> urls = new ArrayList<>();

        // 上传所有文件
        for (MultipartFile file : files) {
            if (file.isEmpty()) continue;

            try {
                String originalFilename = file.getOriginalFilename();
                String extension = "";
                if (originalFilename != null && originalFilename.contains(".")) {
                    extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                }
                String fileName = UUID.randomUUID().toString() + extension;
                File dest = new File(UPLOAD_DIR + fileName);

                file.transferTo(dest);
                String fileUrl = "http://localhost:8080/uploads/rescue_photos/" + fileName;
                urls.add(fileUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (urls.isEmpty()) {
            res.put("code", 500);
            res.put("msg", "没有文件上传成功");
            return res;
        }

        // 如果 rescueId 为空（新增场景），只返回URLs，让前端保存时一起提交
        if (rescueId == null) {
            String joinedUrls = String.join(",", urls);
            res.put("code", 200);
            res.put("msg", "上传成功");
            res.put("urls", urls);
            res.put("joinedUrls", joinedUrls);
            return res;
        }

        // 如果 rescueId 存在（编辑场景），更新现有记录
        RescueInfo existing = rescueInfoServicel.getById(rescueId);
        if (existing == null) {
            res.put("code", 404);
            res.put("msg", "未找到该救助记录");
            return res;
        }

        // 拼接新的 URLs
        String joinedUrls = String.join(",", urls);

        // 合并旧的和新的URLs（防止覆盖已有图片）
        String oldPhotos = existing.getPhoto();
        String finalPhoto = (oldPhotos == null || oldPhotos.isEmpty())
                ? joinedUrls
                : oldPhotos + "," + joinedUrls;

        // 更新数据库
        existing.setPhoto(finalPhoto);
        boolean success = rescueInfoServicel.updateById(existing);

        if (success) {
            res.put("code", 200);
            res.put("msg", "上传成功");
            // 返回所有图片URL列表
            List<String> allPhotos = Arrays.asList(finalPhoto.split(","));
            res.put("urls", allPhotos);
        } else {
            res.put("code", 500);
            res.put("msg", "数据库更新失败");
        }

        return res;
    }




}
